﻿using System;
using System.Collections;
using System.Threading;

namespace SDFL.KeyPoints.DesignPattern.Singleton.Realworld
{
    // "Singleton"
    class LoadBalancer
    {
        // Fields
        private static LoadBalancer balancer;
        private ArrayList servers = new ArrayList();
        private Random random = new Random();

        // Lock synchronization object 
        private static object syncLock = new object();

        // Constructors (protected)
        protected LoadBalancer()
        {
            // List of available servers
            servers.Add("ServerI");
            servers.Add("ServerII");
            servers.Add("ServerIII");
            servers.Add("ServerIV");
            servers.Add("ServerV");
        }

        // Methods
        public static LoadBalancer GetLoadBalancer()
        {
            // Support multithreaded applications through
            // "Double checked locking" pattern which avoids
            // locking every time the method is invoked
            if (balancer == null)
            {
                lock (syncLock)
                {
                    if (balancer == null)
                        balancer = new LoadBalancer();
                }
            }
            return balancer;
        }

        // Properties
        public string Server
        {
            get
            {
                // Simple, but effective random load balancer
                int r = random.Next(servers.Count); // load balance logic
                return servers[r].ToString();
            }
        }
    }
}

